/***************** Modification History ***********************************
   @doc
   @module CSCLNT.c - Ethernet support via TCP Client Server
   @end

$Log: /SoftPay/Source/CSCLNT/CSCLNT.c $
**************************************************************************
   Copyright (C) 2003 by VeriFone, Inc.

   All rights reserved.  No part of this software may be reproduced,
   transmitted, transcribed, stored in a retrieval system, or translated
   into any language or computer language, in any form or by any means,
   electronic, mechanical, magnetic, optical, chemical, manual or otherwise,
   without the prior written permission of VeriFone, Inc.
---------------------------------------------------------------------------*/

#include <project.h>

#ifdef CSCLNT_DEFINED

#define DEBUG_CSCLNT
#ifdef DEBUG_CSCLNT
 #define DEBUG_95
#endif

//extern "C"
//{
#include <string.h>
#include <svc.h>
#include <errno.h>
#include <acldev.h>

#include <define.h>
#include <transact.h>
#include <mem.h>
#include <msgfuncs.h>
#include <vmac.h>
#include <confProto.h>
#include <tblutil.h>
#include <msg.h>
#include <confio.h>
#include <util.h>
#include <ui.h>
#include <logo.h>
#include <form.h>
#include <init.h>
#include <comm.h>
#include <protocol.h>
#include <operate.h>
#include <modemmsg.h>
#include <txoinc.h>
//#include <msgethr.h>//TODO
#include <spdebug.h>
#include <oper.h>
#include <table.h>
#include <funcids.h>

#ifdef FHANDLE
#undef FHANDLE
#endif

//VMAC Specific
#include <varrec.h>
#include <eeslapi.h>
#include <mamevent.h>


// Comm Server
#include "..\vcssrc\vcsInterFace.h"

// CS Client
#include "..\vcssrc\CSclnt.h"
//#include "..\hsbhsrc\hsbhmsg.h"
//}

//int StatusIDs[MAX_STATUS_FIELDS];
short StatusIDs[MAX_STATUS_FIELDS];
short shSignalStrength=0,shConnectionStatus=0;
extern int hConsoleS;
//extern int inPrintISOPacket(VS_BOOL fSendPacket, unsigned char *pucMessage, int inLen);///ivan



//RCPT_FIELDS srRcpt;

// Function: inInitializeCSCLNTComm()
// This function maps the appropirate functions to the inteface
//
void vdInitializeCSCLNTComm (COMM_OBJECT *obCommunication)
{
//    pdebug (("vdInitializeCSCLNTComm:In2"));
    //obCommunication->inLinkType = CSCLNT_COMM;
    //obCommunication->fLinkUp = VS_FALSE;
    obCommunication->inInitialize = (PFI_VD)inInitCSCLNTComm;
    obCommunication->inBegin = (PFI_PFOR_BEGIN)inBeginCSCLNTComm;
    obCommunication->inCheck = (PFI_VD)inCheckCSCLNTComm;
    obCommunication->inSend = (PFI_PFOR_SEND)inSendCSCLNTComm;
    obCommunication->inReceive = (PFI_PFOR_RES)inReceiveCSCLNTComm;
    obCommunication->inEnd = (PFI_VD)inEndCSCLNTComm;
    obCommunication->inFlush = (PFI_VOID)inFlushCSCLNTComm;
    obCommunication->inDeinitialize = (PFI_VD)inDeInitCSCLNTComm;
} // end vdInitializeCSCLNTComm


//
// Function: inInitCSCLNTComm()
// Description: This should be the first call to the library. This inits the library
//
int inInitCSCLNTComm (COMM_OBJECT *pobCommunication)
{
//int inErr;
//int inSH;
//int inNative;
short inErr, inSH, inNative;
CSCLNT_OBJECT *pobCSCLNT;

	MEMCLR(pobCSCLNT, sizeof(pobCSCLNT));

    //pdebug (("*****inInitCSCLNTComm*****"));
    if ((pobCommunication->Data = (void *)pchAlloc(sizeof(CSCLNT_OBJECT))) == NULL)
        {
            //pdebug (("inInitCSCLNTComm:Err:No Memory"));
            return(VS_ERROR);
        }

    // Initialize the Object
    pobCSCLNT = (CSCLNT_OBJECT *)pobCommunication->Data;
    pobCSCLNT->shECTIndex = -1; // ECT Indexes are 0 relative
    pobCSCLNT->bConnStatus = VS_FALSE;
    pobCSCLNT->bInSession = VS_FALSE;
    pobCSCLNT->shSessHandle = -1; // undefined

    // Initialize element fLinkUp
    pobCommunication->fLinkUp = VS_FALSE;

    // Obtain the Version info from the server
//	if (shGetVersion(pobCSCLNT, szVersion) == VS_SUCCESS)
//	{
//		pdebug (("inInitCSCLNTComm:Ver:%s", szVersion));
//	}

    // Initailze the event buffer
    vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

    // Send Event to server
   //pdebug (("inInitCSCLNTComm:Event:VCS_EVT_INIT_REQ:%d",VCS_EVT_INIT_REQ));
    if (shSendEventToSvr(VCS_EVT_INIT_REQ, pobCSCLNT, VS_TRUE) == VS_ERROR)
    {
            return VS_ERROR;
    }

    // Set up event to recv from server
    pobCSCLNT->shEsmCount = 1;
    pobCSCLNT->shEsmList[0] = VCS_EVT_INIT_RESP;

    // Read event from server
    if ((shReadEventFromSvr(10000L, pobCSCLNT)) == VS_ERROR) //TODO - timeout
        {
            //pdebug (("inInitCSCLNTComm:Event:shReadEventFromSvr:ERROR"));
            return VS_ERROR;
        }

    //pdebug (("inInitCSCLNTComm:Event:VCS_EVT_INIT_RESP:%d",VCS_EVT_INIT_RESP));

    // Extract data from event buffer
    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);
	//inPrintISOPacket("EventDataBuf", (unsigned char *)pobCSCLNT->EventDataBuf, 64);

#if 0
	#ifdef _TARG_68000
	#elif __thumb
	#endif
#endif

	#ifdef _TARG_68000
    	shVarGetUnsignedInt(VCS_FLD_SESS_HANDLE, (unsigned int *) &inSH );
    	shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned int *) &inErr);
    	shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned int *) &inNative);
	#elif __thumb
    	if(shVarGetUnsignedInt(VCS_FLD_SESS_HANDLE, (unsigned short *) &inSH ) != 0)
    	{
				//pdebug(("VCS_FLD_SESS_HANDLE_____"));
    	}
    	if(shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr) != 0)
    	{
				//pdebug(("VCS_FLD_SESS_ERROR_____"));
    	}
    	if(shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative) != 0)
		{
				//pdebug(("VCS_FLD_SESS_NATIVE_____"));
    	}
	#endif

    //shVarGetUnsignedInt(VCS_FLD_SESS_HANDLE, (unsigned short *) &inSH );
    //shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr);
    //shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative);
    //pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_HANDLE:%d", inSH));
    //pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_ERROR:%d", inErr));
    //pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_NATIVE:%d", inNative));

    if (inErr == VS_SUCCESS)
	{
            pobCSCLNT->shSessHandle = inSH;
            pobCSCLNT->bInSession = VS_TRUE;
            return (VS_SUCCESS);
    }
    else
        {
//            vdEthrDisplayMessage(ETHR_CS_INIT_ERR, inErr); //TODO MESSAGE
            pobCSCLNT->inNativeErr = inNative;
            return (VS_ERROR);
        }

} // end inInitCSCLNTComm

//
// Function: inBeginCSCLNTComm
// Description: Establishes connection sets up context
//
int inBeginCSCLNTComm(COMM_OBJECT *pobCommunication, int inIndex, VS_BOOL fUnusedParameter)
{
	CSCLNT_OBJECT *pobCSCLNT;
	TRANSACTION_OBJECT *pobTran;
	int inOpCode;
	short inErr, inSH, inNative;
	short port=60;
    int inRetryCount;
    int inResult;
	char szHostIPAddress[25+1];
	int retval;

	//pdebug (("*****inBeginCSCLNTComm*****"));

    if(inLoadTCPRec(0)!=VS_SUCCESS)
    {
    	//vdDisplayMessageFromFile(IPT_ERR_MSG21, WARNING_MSG);
    	return VS_ERR;
    }

	inRetryCount = shGetIPTries();
	inRetryCount = inRetryCount * 2;
	//pdebug(("*****inRetryCount=%d",inRetryCount));

	/*****************************************************************************/
	//try to reconnect if connection attempt fails
	/*****************************************************************************/
	vdClearNonTitleLines();
	vdDisplayAt(1, 8, "PROCESSING",CLR_LINE);


	while(inRetryCount)
	{


		pobCSCLNT = (CSCLNT_OBJECT *)pobCommunication->Data;

		// Initailze the event buffer
    	vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
    	ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);



		#ifdef _TARG_68000
			shVarAddUnsignedInt(VCS_FLD_CONN_HOSTSSL, (unsigned int)0);
		#elif __thumb
			shVarAddUnsignedInt(VCS_FLD_CONN_HOSTSSL, (unsigned short)0);
		#endif

    	pobTran=pstGet_pobTran();
    	if(pobTran==NULL)
    	{

        	//pdebug(("inBginCSCLNT:pobTran ERROR"));
        	return(VS_ERROR);
    	}

		//pdebug(("inRetryCount=%d",inRetryCount));
		memset(szHostIPAddress, 0, sizeof(szHostIPAddress));
		if (inRetryCount%2)
		{

			strcpy(szHostIPAddress, szGetHostSecondaryIP());
		}
		else
		{

			strcpy (szHostIPAddress , szGetHostPrimaryIP());
		}

		inRetryCount--;

		#ifdef _TARG_68000
			shVarAddData(VCS_FLD_CONN_URL, (unsigned char *)szHostIPAddress,(unsigned int)strlen(szHostIPAddress));
			shVarAddUnsignedInt((unsigned int)VCS_FLD_CONN_PORT, (unsigned int)shGetIPPort());
		#elif __thumb
			shVarAddData(VCS_FLD_CONN_URL, (unsigned char *)szHostIPAddress,(unsigned short)strlen(szHostIPAddress));
			shVarAddUnsignedInt(VCS_FLD_CONN_PORT, (unsigned short)shGetIPPort());
		#endif

		//pdebug(("URL=%s,PORT=%d",szHostIPAddress,shGetIPPort()));

		// Send Event to server
		if(shSendEventToSvr(VCS_EVT_CONN_REQ, pobCSCLNT, VS_TRUE) == VS_ERROR)
			continue;//return VS_ERROR;

		// Set up event to recv from server
		pobCSCLNT->shEsmCount = 1;
		pobCSCLNT->shEsmList[0] = VCS_EVT_CONN_RESP;

		// Read event from server
		if ((shReadEventFromSvr(10000L, pobCSCLNT)) == VS_ERROR) //TODO TIMEOUT
			continue;//return VS_ERROR;

		ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);
		#ifdef _TARG_68000
    		shVarGetUnsignedInt(VCS_FLD_SESS_HANDLE, (unsigned int *) &inSH );
    		shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned int *) &inErr);
    		shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned int *) &inNative);
		#elif __thumb
    		shVarGetUnsignedInt(VCS_FLD_SESS_HANDLE, (unsigned short *) &inSH );
   	 		shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr);
    		shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative);
		#endif

    	//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_HANDLE:%d", inSH));
    	//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_ERROR:%d", inErr));
    	//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_NATIVE:%d", inNative));

		// Check for, display and return
		if (inErr > 0)
		{
			pobCSCLNT->inNativeErr = inNative;
			continue;
		}
		pobCSCLNT->bConnStatus = VS_TRUE;
		pobCommunication->fLinkUp = VS_TRUE;

		/*****************************************************************************/
		//check if the host is available
		/*****************************************************************************/

		//pdebug (("*****inCheckCSCLNTComm*****"));
    	pobCSCLNT = (CSCLNT_OBJECT *)pobCommunication->Data;

    	retval=shRequestStatus(pobCSCLNT,VS_TRUE);



    	if(retval==VS_SUCCESS)
    	{

			retval=shGetStatus(pobCSCLNT);
    	}

    	if(retval!=VS_SUCCESS)
        {

			pobCSCLNT->bConnStatus = VS_FALSE;
            pobCommunication->fLinkUp = VS_FALSE;
            pobCSCLNT->bConnStatus = VS_TRUE;
            obCommunication.inEnd(&obCommunication);
            continue;//return VS_ERROR;
        }

    	if(pobCSCLNT->bConnStatus==VS_TRUE)
        {

			pobCommunication->fLinkUp = VS_TRUE;
			return VS_SUCCESS;
        }

    	if(pobCSCLNT->bConnStatus==VS_FALSE)
        {

			pobCommunication->fLinkUp = VS_FALSE;
            continue;//return VS_ERROR;
        }



		return VS_SUCCESS;
	}

	//pdebug(("inBeginCSCLNTComm - ERROR"));
	return(VS_ERROR);
} // inBeginCSCLNTComm

//
// Function: inFlushCSCLNTComm
// Description: Does nothing.
//
int inFlushCSCLNTComm(void)
{
    return(VS_SUCCESS);
} // end inFlushCSCLNTComm


//
// Function: inEndCSCLNT
// Description: Terminates the communication with the host.
// Note: The context with the host is still maintained
//
int inEndCSCLNTComm(COMM_OBJECT *pobCommunication)
{
	int inErr;
	int inNative;
	CSCLNT_OBJECT *pobCSCLNT;

	pobCSCLNT = (CSCLNT_OBJECT *)pobCommunication->Data;
	//pdebug(("^^^^^inEndCSCLNTComm^^^^^"));

	if (pobCSCLNT->bConnStatus == VS_FALSE)
	{
			//pdebug(("inEndCSCLNTComm2 == FALSE"));
// TODO:     KV1 Remove
//		pobCommunication->fLinkUp = VS_FALSE;
		return(VS_SUCCESS);
	}

	// Initailze the event buffer
    //vVarInitRecord(pobCSCLNT->EventDataBuf, sizeof(pobCSCLNT->EventDataBuf), 0);
    vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

	// Send Event to server
	if (shSendEventToSvr(VCS_EVT_DISC_REQ, pobCSCLNT, VS_TRUE) == VS_ERROR)
		return VS_ERROR;

	// Set up event to recv from server
	pobCSCLNT->shEsmCount = 1;
	pobCSCLNT->shEsmList[0] = VCS_EVT_DISC_RESP;

	// Read event from server
	if ((shReadEventFromSvr(10000L, pobCSCLNT)) == VS_ERROR) //TODO TIMEOUT
		return VS_ERROR;

	// Extract data from event buffer
	ushInitStandardFlexi(pobCSCLNT->EventDataBuf);
	shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr);
	shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative);
	//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_ERROR:%d", inErr));
	//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_NATIVE:%d", inNative));

	// Check for, display and return
    if (inErr > 0)
    {
		//vdEthrDisplayMessage(ETHR_HOST_DISCONNECT_ERR, inErr); //TODO MESSAGE
		pobCSCLNT->inNativeErr = inNative;
		return(VS_ERROR);
    }

	pobCSCLNT->bConnStatus = VS_FALSE;
// TODO:     KV1 Remove
//	pobCommunication->fLinkUp = VS_FALSE;

	return(VS_SUCCESS);
} //end inEndCSCLNTComm


//
// Function: inDeInitCSCLNTComm()
// Deinits the library and frees allocated memory
// This should the the last call to the library
//
int inDeInitCSCLNTComm (COMM_OBJECT *pobCommunication)
{
    CSCLNT_OBJECT *pobCSCLNT;
	//int inErr = VS_SUCCESS;
	short inNative;
	short inErr=VS_SUCCESS;//,inNative;

	pobCSCLNT = (CSCLNT_OBJECT *)pobCommunication->Data;

	// Release the session handle if one is present
	if (pobCSCLNT->bInSession == VS_TRUE)
	{
		while(VS_TRUE)
		{
			// Initailze the event buffer
		    //vVarInitRecord(pobCSCLNT->EventDataBuf, sizeof(pobCSCLNT->EventDataBuf), 0);
		    vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
		    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

			// Send Event to server
			if ((inErr = shSendEventToSvr(VCS_EVT_DEINIT_REQ, pobCSCLNT, VS_TRUE)) == VS_ERROR)
				break;

			// Set up event to recv from server
			pobCSCLNT->shEsmCount = 1;
			pobCSCLNT->shEsmList[0] = VCS_EVT_DEINIT_RESP;

			// Read event from server
			if ((inErr = shReadEventFromSvr(10000L, pobCSCLNT)) == VS_ERROR) //TODO TIMEOUT
				break;

			// Extract data from event buffer
			ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);
			shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr);
			shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative);
			//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_ERROR:%d", inErr));
			//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_NATIVE:%d", inNative));
			if (inErr > 0)
			{
				inErr = VS_ERROR;
				pobCSCLNT->inNativeErr = inNative;
			}
			break;
		} // end while
	}
    vdFree((char *)pobCommunication->Data);
    pobCommunication->Data = NULL;
    pobCommunication->inLinkType = NO_COMM;
    //srGDS.fWirelessActive = VS_FALSE;

	return (VS_SUCCESS);
} // end inDeInitCSCLNTComm


//
// Function: inCheckCSCLNTComm()
// Returns the connection status VS_TRUE if connected VS_FALSE otherwise.
//
int inCheckCSCLNTComm (COMM_OBJECT *pobCommunication)
{
	return(VS_SUCCESS);
} // end inCheckCSCLNTComm

//
// Function: inSendCSCLNTComm
// Sends data and returns the number of bytes sent. Returns VS_ERROR(-1) in case of error
//
int inSendCSCLNTComm
(
	COMM_OBJECT *pobCommunication,
    char        *pchSendBuff,
    int          inSendSize,
    VS_BOOL      fConfirmSend, // unused
    int			 inTimeout, // unused
    long		 lnMessage
)
{
	CSCLNT_OBJECT *pobCSCLNT;
//	int inErr;
//	int inNative;
	short inErr,inNative;
	unsigned char temp_send[500];
	unsigned char temp[500];

	//pdebug (("*****inSendCSCLNTComm*****"));
	vdClearNonTitleLines();
	vdDisplayAt(1, 8, "SENDING",CLR_LINE);

	pobCSCLNT = (CSCLNT_OBJECT *)pobCommunication->Data;

	// Display on screen
	//if (lnMessage)
	//	vdDisplayMessageFromFile(lnMessage, STATUS_MSG);//TODO
	// Initailze the event buffer
    //vVarInitRecord(pobCSCLNT->EventDataBuf, sizeof(pobCSCLNT->EventDataBuf), 0);
    vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

	//albert_d1 to add length to the message
	memset(temp_send,0,sizeof(temp_send));
	memset(temp,0,sizeof(temp));
	sprintf((char *)temp,"%04d",inSendSize);
 	SVC_DSP_2_HEX((char *) temp ,(char *) temp_send , 2);
	memcpy(&temp_send[2],pchSendBuff,inSendSize);
	//inSendSize+=2;
	//end albert_d1 to add length to the message
	//inPrintISOPacket("temp_send", temp_send, inSendSize+2);
	// Add parameters to send to server
	//LOG_PRINTFF((0x8l,temp_send, inSendSize+2));

	shVarAddUnsignedInt(VCS_FLD_SEND_BUFSIZE, (unsigned short)inSendSize+2);

	// Send Event to server
	if (shSendEventToSvr(VCS_EVT_SEND_REQ, pobCSCLNT, VS_TRUE) == VS_ERROR)
	{
		//vdDisplayAt(1, 8, "REQ-ERROR",CLR_LINE);
		//get_char();
		return VS_TIMEOUT;	//return VS_ERROR;
	}

	// Send data as raw data

	//shSendDataToClient(pchSendBuff, inSendSize, pobCSCLNT);

	//albert_d1 to add length to the message
	shSendDataToClient((char *)temp_send, inSendSize+2, pobCSCLNT);
	//end albert_d1 to add length to the message

	// Display data sent to host
//	LOG_HEX_Buf((unsigned char *)pchSendBuff, inSendSize, "T->H");

	// Set up event to recv from server
	pobCSCLNT->shEsmCount = 1;
	pobCSCLNT->shEsmList[0] = VCS_EVT_SEND_RESP;

	// Read event from server
	if ((shReadEventFromSvr(10000L, pobCSCLNT)) == VS_ERROR) //TIMEOUT
	{
		//vdDisplayAt(1, 8, "REQ-ERROR1",CLR_LINE);
		//get_char();

		return VS_TIMEOUT;//return VS_ERROR;
	}

	// Extract data from event buffer
	ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);
	shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr);
	shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative);
	//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_ERROR:%d", inErr));
	//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_NATIVE:%d", inNative));

	// Check for, display and return
    if (inErr > 0)
    {
		//vdDisplayAt(1, 8, "REQ-ERROR3",CLR_LINE);
		//get_char();
		//vdEthrDisplayMessage(ETHR_SEND_ERR, inErr); //TODO
		pobCSCLNT->inNativeErr = inNative;
		return VS_TIMEOUT;//return(VS_ERROR);
    }

	//vdDisplayAt(1, 8, "REQ-OK",CLR_LINE);
	//get_char();
	return (inSendSize);
} // inSendCSCLNTComm



//
// Function: inCSCLNTComm()
// Returns the number of bytes read or VS_ERROR (-1) if it has failed
//
int inReceiveCSCLNTComm
(
	COMM_OBJECT *pobCommunication,
    char        *pchReceiveBuff,
    int          inReceiveSize,
    int          inReceiveTimeout,
    long		 lnMessage
)
{
	CSCLNT_OBJECT *pobCSCLNT;
	//int inErr;
	//int inNative;
	//int inTotalRecv;
	short inErr,inNative,inTotalRecv;
	unsigned char temp_receive[500];

	pobCSCLNT = (CSCLNT_OBJECT *)pobCommunication->Data;

	vdClearNonTitleLines();
	vdDisplayAt(1, 8, "RECEIVING",CLR_LINE);

	//pdebug (("*****inReceiveCSCLNTComm*****"));
	// Display on screen
	//if (lnMessage)
	//	vdDisplayMessageFromFile(lnMessage, STATUS_MSG); //TODO

	// Initailze the event buffer
    //vVarInitRecord(pobCSCLNT->EventDataBuf, sizeof(pobCSCLNT->EventDataBuf), 0);
    vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

	// Add parameters to send to server
    shVarAddUnsignedInt(VCS_FLD_RECV_BUFSIZE, (unsigned short)inReceiveSize);
    shVarAddUnsignedInt(VCS_FLD_RECV_TIMEOUT, (unsigned short)(inReceiveTimeout/100));

	// Send Event to server
	if (shSendEventToSvr(VCS_EVT_RECV_REQ, pobCSCLNT, VS_TRUE) == VS_ERROR)
	{
//		vdDisplayAt(1, 8, "RESP-ERROR1",CLR_LINE);
//		get_char();

		return VS_TIMEOUT;//return VS_ERROR;
	}

	// Set up event to recv from server
	pobCSCLNT->shEsmCount = 1;
	pobCSCLNT->shEsmList[0] = VCS_EVT_RECV_RESP;

	// Read event from server
	if ((shReadEventFromSvr(10000L, pobCSCLNT)) == VS_ERROR) //TODO
	{
//		vdDisplayAt(1, 8, "RESP-ERROR2",CLR_LINE);
//		get_char();
		return VS_TIMEOUT;//return VS_ERROR;
	}

	// Extract data from event buffer
	ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);
	shVarGetUnsignedInt(VCS_FLD_RECV_BUFSIZE, (unsigned short *) &inTotalRecv);
	shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr);
	shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative);

	pdebug (("inInitCSCLNTComm:Data:VCS_FLD_RECV_BUFSIZE:%d", inTotalRecv));
	pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_ERROR:%d", inErr));
	pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_NATIVE:%d", inNative));

	// Check number of bytes received
    if (inTotalRecv < 0 || inErr > 0)
    {
//		vdDisplayAt(1, 8, "RESP-ERROR3",CLR_LINE);
//		get_char();
		//vdEthrDisplayMessage(ETHR_RECV_ERR, inErr);
		pobCSCLNT->inNativeErr = inNative;
		return VS_TIMEOUT;//return(VS_ERROR);
    }

    // Raw read data until none available
	pobCSCLNT->shEsmCount = 1;
	pobCSCLNT->shEsmList[0] = VCS_EVT_DATA_RAW;

	//albert_d1 remove the 2bytes length
	memset(temp_receive,0,sizeof(temp_receive));
	//inErr = shRecvDataFromClient(pchReceiveBuff, inTotalRecv, pobCSCLNT);
	inErr = shRecvDataFromClient((char *)temp_receive, inTotalRecv, pobCSCLNT);
	//inPrintISOPacket("temp_receive", temp_receive, inTotalRecv);
	//LOG_PRINTFF((0x8l,temp_receive, inTotalRecv));

	memcpy(pchReceiveBuff,	&temp_receive[2],inTotalRecv-2);
	//albert_d1 removed the 2byte length
    if (inErr == VS_SUCCESS)
    {
//		vdDisplayAt(1, 8, "RESP-ERROR4",CLR_LINE);
//		get_char();
    	return inTotalRecv-2;
    }
//		vdDisplayAt(1, 8, "RESP-OK",CLR_LINE);
//		get_char();
	return VS_TIMEOUT;//return VS_ERROR;
} // end inReceiveCSCLNTComm

//
// Function: shSendEventToSvr()
// Description: sends an event to server. Keeps trying until it succeeds
//
static short shSendEventToSvr(unsigned int inSendEvent, CSCLNT_OBJECT *pobCSCLNT, VS_BOOL fRetry)
{
int shRetVal = VS_ERROR;
int count = 0;
int shErr;
int inTimeoutID;
int inDelayID;
long lnEvent;
long lnDelayMS;

    // Reading any pending items in the queue
    vdReadPendingEventsInQ();

    //pdebug (("shSendEventToSvr:Evt:%d:%d", inSendEvent, fRetry));

    // Add session handle if in session
    if (pobCSCLNT->bInSession == VS_TRUE)
    {
       shVarAddUnsignedInt(VCS_FLD_SESS_HANDLE, pobCSCLNT->shSessHandle);
	   //pdebug (("shSendEventToSvr:VCS_FLD_SESS_HANDLE:%d", pobCSCLNT->shSessHandle));
     }

	#ifdef _TARG_68000
		shGetRecordLength(pobCSCLNT->EventDataBuf, (int *)&pobCSCLNT->inEventDataSize);
	#elif __thumb
		shGetRecordLength(pobCSCLNT->EventDataBuf, (short *)&pobCSCLNT->inEventDataSize);
	#endif
	//pdebug (("shSendEventToSvr:EventDataSize:%d", pobCSCLNT->inEventDataSize));

    // Send event
    if ( (inTimeoutID = set_timer(10000L, SPBASE_TIMER1)) >= 0)
        {
            while (VS_TRUE)
                {
						shErr = EESL_send_event((const char *)COMM_SVR, (unsigned short)inSendEvent,
						(unsigned char *)pobCSCLNT->EventDataBuf, (unsigned short)pobCSCLNT->inEventDataSize);
                    //shErr = EESL_send_event(COMM_SVR, inSendEvent, pobCSCLNT->EventDataBuf, pobCSCLNT->inEventDataSize);
                    if ( shErr == 0 )
                        {
                            // If the event was successfully sent return immediately
                            shRetVal = VS_SUCCESS;
                            break;
                        }
                    if ( shErr  !=  EESL_SEND_FAILURE )
                        {
                            pobCSCLNT->shTCPClientErr = CSCLNT_SENDERR;
                            pobCSCLNT->inNativeErr = shErr;
                            //pdebug(("shSendEventToSvr:SendErr:%d", shErr));
                            break;
                        }
/*                    // MLOULOU
                    // if non blocking do not wait if commserver is busy
                    if ( fRetry )
                        {
                            pdebug (("DON'T RETRY SEND"));
                            break;
                        }
*/
                    lnDelayMS = ((count++ % 4) == 0 ? CSCLNT_MSEC_1000 : CSCLNT_MSEC_100);
                    //pdebug (("count=%d",count));
                    //pdebug (("lnDelayMS=%ld",lnDelayMS));
                    if ( (inDelayID = set_timer(lnDelayMS, SPBASE_TIMER2)) < 0)
                        {
                            break;
                        }
                    lnEvent = 0L;
                    while (     ((lnEvent & SPBASE_TIMER1) != SPBASE_TIMER1) &&
                                    ((lnEvent & SPBASE_TIMER2) != SPBASE_TIMER2)        )
                        {
                            lnEvent = wait_event();
                        }

                    //pdebug (("lnEvent=%ld",lnEvent));

                    clr_timer(inDelayID);

                    // Timeout timer
                    if ( (lnEvent & SPBASE_TIMER1) == SPBASE_TIMER1 )
                        {
                            //pdebug (("Timeout timer"));
                            break;
                        }

                    // Delay timer
                    if ( (lnEvent & SPBASE_TIMER2) == SPBASE_TIMER2 )
                        {
                            //pdebug (("Delay timer"));
                        }

                };

            clr_timer(inTimeoutID);

        }

    return shRetVal;

}


//
// Function: shReadEventFromSvr()
// Description: Reads the next event from the VMAC event queue. It waits for msRespTimeout (milliSec)
// before it returns. If a timeout occurs then it is an error and it returns
// Param 1: msRespTimeout -- time in milliSec the function waits for a response from the Server
// Param 2: pobCSCLNT -- object containing the event details
//
static short shReadEventFromSvr(long msRespTimeout, CSCLNT_OBJECT *pobCSCLNT)
{
short shRetVal = VS_SUCCESS;
short shError =0;
int inTimerID;
long osEvent;
int inEventID;

    // Initialize Error to no error
    pobCSCLNT->shTCPClientErr = CSCLNT_NOERROR;
    pobCSCLNT->inNativeErr = 0;

    // Set timer event
    while (shRetVal == VS_SUCCESS)
        {
            // If timer is non-negative then the result is OK
            if ((inTimerID = set_timer(msRespTimeout, SPBASE_TIMER1)) >= 0)
                {
                    break;
                }

            // check if timer is valid
            if (inTimerID == -EINVAL)
                {
                    //pdebug (("shReadEventFromSvr:InvalidTimerValue"));
                    pobCSCLNT->shTCPClientErr = CSCLNT_INVALID;
                    pobCSCLNT->inNativeErr = EINVAL;
                    shRetVal = VS_ERROR;
                    shError = -1;
                }

            // Try again if no timers are available after a wait
            if (inTimerID == -ENOSPC)
                {
                    //pdebug (("shReadEventFromSvr:TimersUnavailable"));
                    SVC_WAIT((unsigned int)CSCLNT_MSEC_250);
                    continue;
                }
        } // end while

    while (shRetVal == VS_SUCCESS)
        {
            // Block until an OS or timer event occurs
            //pdebug (("shReadEventFromSvr:WaitingForOSEvent"));
            osEvent = wait_event();

            // If this is a timer event, then we got no VMAC event
            if (osEvent & EVT_TIMER)
            {
						//pdebug (("%%%osEvent & EVT_TIMER%%%"));
                    	if ((osEvent & SPBASE_TIMER1) == SPBASE_TIMER1)
                 		{
                            //pdebug (("shReadEventFromSvr:TimeoutOnVMACEvent"));
								//albert_d1
                            pobCSCLNT->shTCPClientErr = CSCLNT_TIMEOUT;
                            shRetVal = VS_ERROR;
                            shError = -2;
								continue;
                    	}
						//continue;
            }
			 //vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
    		 //ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

	           // Read VMAC event
   			 #ifdef _TARG_68000
            if ((!EESL_queue_count()) ||
                    (inEventID = EESL_read_cust_evt((unsigned char *)pobCSCLNT->EventDataBuf, (int)COMMSVR_EVENT_DATA_SIZE,
                    (unsigned int *)&pobCSCLNT->inEventDataSize, (char *)&pobCSCLNT->EventSenderName)) == 0)
			#elif __thumb
            if ((!EESL_queue_count()) ||
                    (inEventID = EESL_read_cust_evt((unsigned char *)pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE,
                    (unsigned short *)&pobCSCLNT->inEventDataSize, (char *)&pobCSCLNT->EventSenderName)) == 0)
            #endif
                {
                    // Not a VMAC Event for me
                    //pdebug (("shReadEventFromSvr:Not a VMAC Event for me:%d",inEventID));
                    continue;
                }
            //inPrintISOPacket("shReadEventFromSvr:", (unsigned char *)pobCSCLNT->EventDataBuf, 120);
            // Verify Sender
            if (shVerifySender(pobCSCLNT) == VS_ERROR)
                {
                    //pdebug (("shReadEventFromSvr:EESL:UnknownEventSender"));
                    continue;
                }

            // Verify it was anticipated event
            if (shVerifyEvent(inEventID, pobCSCLNT) == VS_ERROR)
                {
                    //pdebug (("shReadEventFromSvr:UnexpectedEvent:Discarding"));
                    // pobCSCLNT->shTCPClientErr  set to CSCLNT_BADEVENT
                    continue;
                }

            // Got Correct Event from Server
            break;
        }

    // Clear timer
    if ( inTimerID >= 0 )
        {
            clr_timer(inTimerID);
        }

    if ( shRetVal == VS_SUCCESS )
        {
            // Invalid parameters passed to the read event
            if (inEventID == EESL_INVALID_PARAMETER)
                {
                    //pdebug (("shReadEventFromSvr:EESL:InvaildParameters"));
                    pobCSCLNT->shTCPClientErr = CSCLNT_INVALID; // Invalid data
                    pobCSCLNT->inNativeErr = EESL_INVALID_PARAMETER;
                    shRetVal = VS_ERROR;
                    shError = -3;
                }
        }

    if ( shRetVal == VS_SUCCESS )
        {
            // Buffer too small
            if (inEventID == EESL_ERROR_BUFFER_TOO_SMALL)
                {
                    //pdebug (("shReadEventFromSvr:EESL:BufferTooSmall"));
                    pobCSCLNT->shTCPClientErr = CSCLNT_BUFSIZE;
                    pobCSCLNT->inNativeErr = EESL_ERROR_BUFFER_TOO_SMALL;
                    shRetVal = VS_ERROR;
                    shError = -4;
                }
        }

    if ( shRetVal == VS_SUCCESS )
        {
            pobCSCLNT->inEventID = inEventID;
        }

#if 0
{
int loop = 10;

    while ( shRetVal == VS_ERROR && loop--)
        {
            pdebug (("shRetVal = %d",shRetVal));
            pdebug (("shError = %d",shError));
            switch (shError)
                {
                    case -5:
                        pdebug (("EventSenderName=%s",(char *)pobCSCLNT->EventSenderName));
                        break;
                    case -6:
                        pdebug (("shEsmList[0]=%d",pobCSCLNT->shEsmList[0] ));
                        pdebug (("inEventID=%d",inEventID));
                        break;
                }
            SVC_WAIT (1000L);
        }
}
#endif
    return shRetVal;

}

//
// Function: shVerifySender()
// Description: Verifies that the name of sender of the VMAC event is as expected.
// Incase of error, shErr and inNativeErr are set.
// Returns: VS_SUCCESS if the name matches, VS_ERORR if it fails
//
static short shVerifySender(CSCLNT_OBJECT *pobCSCLNT)
{
short shRetVal = VS_SUCCESS;

    if (strcmp((char *)pobCSCLNT->EventSenderName, COMM_SVR) != 0)
        {
            pobCSCLNT->shTCPClientErr = CSCLNT_BADSNDR;
            //pdebug (("EventSenderName=%s",(char *)pobCSCLNT->EventSenderName));
        }
	return shRetVal;
} // end shVerifySender

//
// Function: shVerifyExpectedEvents()
// Description: Each event sent to the server evokes a specific set of responses.
// This method verifies that event returned is indeed one of them
// Returns: VS_SUCCESS if the event is present in the list matches, VS_ERORR if it fails
//
static short shVerifyEvent(int inEventID, CSCLNT_OBJECT *pobCSCLNT)
{
short shRetVal = VS_ERROR;
short shIndex;

    for(shIndex = 0; shIndex < pobCSCLNT->shEsmCount; shIndex++)
        {
            if (pobCSCLNT->shEsmList[shIndex] == inEventID)
                {
                    shRetVal = VS_SUCCESS;
                    break;
                }
        }

    if ( shRetVal != VS_SUCCESS )
        {
            pobCSCLNT->shTCPClientErr = CSCLNT_BADEVENT;
            //pdebug (("shEsmList[0]=%d",pobCSCLNT->shEsmList[0] ));
            //pdebug (("inEventID=%d",inEventID));
        }

    return shRetVal;
} // end shVerifyEvent


//
// Function: Read pending events from queue
// Description: Loops thru and reads any pending events in the queue
//
static void vdReadPendingEventsInQ(void)
{
	CSCLNT_OBJECT obCSCLNT;
	CSCLNT_OBJECT *pobCSCLNT = &obCSCLNT;
	int inEventID;

	while(EESL_queue_count() != 0)
    {
		inEventID = EESL_read_cust_evt(pobCSCLNT->EventDataBuf, sizeof(pobCSCLNT->EventDataBuf),
	    	 (unsigned short *)&pobCSCLNT->inEventDataSize, (char *)&pobCSCLNT->EventSenderName);
		//pdebug (("vdReadPendingEventsInQ:Event:%d, %s", inEventID, pobCSCLNT->EventSenderName));
	}
} // end vdReadPendingEventsInQ

#if 0
//
// Function:  vdEthrDisplayMessage()
// Description: Display an Error Message with an error number
//
static void vdEthrDisplayMessage(long lnMsgIndex, int inErr)
{
	char szDispBuf[MESSAGE_SIZE + 1];
	char szMsgBuf[MESSAGE_SIZE + 1];

	TRANSACTION_OBJECT *pobTran;

	pdebug (("vdEthrDisplayMessage:Err:%lx", lnMsgIndex));

	vdGetMessageFromFile(lnMsgIndex, szMsgBuf);
	if (inErr <0)
	{
                vdSGErrorMessage(lnMsgIndex); // to enable message to display at the end of the transaction
		  vdGetMessageFromFile(lnMsgIndex, szDispBuf);
	}
	else
	{
		sprintf(szDispBuf, szMsgBuf, inErr);
		vdDisplayMessage(szDispBuf, ERROR_MSG);
	}
	// Upload msg in transaction if one is present
    pobTran = pstGet_pobTran ();
    if (pobTran)
    {
    	vdSGRespMsg(szDispBuf);
		if (inGGOpCode() == SETTLE_OPERATION)
			vdSetTranError(TXMT_FAIL_ERR_MSG);
    }
} // end vdEthrDisplayMessage
#endif
//
// Function: shSendDataToClient(char *pchReceiveBuff, int inReceiveSize)
// Description: Send data to the client to send to host
//
static short shSendDataToClient(const char *pchSendBuff, const int inSendSize, CSCLNT_OBJECT *pobCSCLNT)
{
	short shMoveSize;
	short shCurrSize;

	shCurrSize = 0;

	while (shCurrSize < inSendSize)
	{
		shMoveSize = inSendSize - shCurrSize;
		if (shMoveSize > sizeof(pobCSCLNT->EventDataBuf))
			shMoveSize = sizeof(pobCSCLNT->EventDataBuf);
		memcpy(pobCSCLNT->EventDataBuf, &pchSendBuff[shCurrSize], shMoveSize);
    	EESL_send_event(COMM_SVR, VCS_EVT_DATA_RAW, pobCSCLNT->EventDataBuf, shMoveSize);
    	shCurrSize += shMoveSize;
	} // end while

	return VS_SUCCESS;
} // end shSendDataToClient

//
// Function: shRecvDataFromClient()
// Description:
//  when done it sends a message to the the client
//

static short shRecvDataFromClient(char *pchReceiveBuff, int inRecvSize, CSCLNT_OBJECT *pobCSCLNT)
{
	short shPendingSize = 0;
	short shCurrSize = 0;
	short shErr = VS_SUCCESS;

	while (VS_TRUE)
	{
		// Read next event from
		if ((shErr = shReadEventFromSvr(10000, pobCSCLNT)) != VS_SUCCESS)
			return shErr;

		if (shCurrSize < inRecvSize)
		{
			shPendingSize = inRecvSize - shCurrSize;
			if (shPendingSize > sizeof(pobCSCLNT->EventDataBuf))
				shPendingSize = sizeof(pobCSCLNT->EventDataBuf);
			memcpy(&pchReceiveBuff[shCurrSize], &pobCSCLNT->EventDataBuf[0], shPendingSize);
			shCurrSize += shPendingSize;
		}

		// Buffer full send to host and message to client
		if (shCurrSize == inRecvSize)
			return shErr;
	} // end while
} // shRecvDataFromClient

//
// Function: shGetVersion()
// Description: Gets Version string from Server. Use this info to determine
//  if Client can communicate this server.
//
static short shGetVersion(CSCLNT_OBJECT *pobCSCLNT, unsigned char *pszVersion)
{
	int inErr;
	unsigned int inDataLeng;

	while(VS_TRUE)
	{
		// Initailze the event buffer
	    //vVarInitRecord(pobCSCLNT->EventDataBuf, sizeof(pobCSCLNT->EventDataBuf), 0);
        vVarInitRecord(pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
	    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

		// Send Event to server
		if ((inErr = shSendEventToSvr(VCS_EVT_VER_REQ, pobCSCLNT, VS_TRUE)) == VS_ERROR)
			break;

		// Set up event to recv from server
		pobCSCLNT->shEsmCount = 1;
		pobCSCLNT->shEsmList[0] = VCS_EVT_VER_RESP;

		// Read event from server
		if ((inErr = shReadEventFromSvr(10000, pobCSCLNT)) == VS_ERROR)
			break;

		// Extract data from event buffer
		ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);
		shVarGetData(VCS_FLD_SESS_VERSION,  pszVersion, 200, (unsigned short *)&inDataLeng);

		// DO NOT LOOP
		break;
	} // end while

	return VS_SUCCESS;
} // end shGetVersion

static short shRequestStatus(CSCLNT_OBJECT *pobCSCLNT, VS_BOOL fRetry)
{
	short shRetVal = VS_SUCCESS;

    // Initailze the event buffer
    //vVarInitRecord(pobCSCLNT->EventDataBuf, sizeof(pobCSCLNT->EventDataBuf), 0);
    //ushInitStandardFlexi(pobCSCLNT->EventDataBuf);
    vVarInitRecord((unsigned char *)pobCSCLNT->EventDataBuf, (short)COMMSVR_EVENT_DATA_SIZE, 0);
    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);

    // Send Staus IDs Buffer
    memset(&StatusIDs, 0, sizeof(StatusIDs));
    StatusIDs[0] = VCS_FLD_CONN_STATUS;
    // MLOULOU
    // KV1 Switched  to used percentage
    //StatusIDs[1] = VCS_FLD_STATUS_SIGNAL_STRENGTH_ACTUAL;
    StatusIDs[1] = VCS_FLD_STATUS_SIGNAL_STRENGTH_PERCNT;
    shVarAddData(VCS_FLD_STATUS_IDS, (unsigned char*)&StatusIDs, (unsigned short)MAX_STATUS_FIELDS);
    // Send Event to server
    shRetVal = shSendEventToSvr(VCS_EVT_STATUS_REQ, pobCSCLNT, fRetry);

    return shRetVal;
}

static short shExtractStatus(CSCLNT_OBJECT *pobCSCLNT)
{
short shRetVal = VS_SUCCESS;
//int inErr;
//int shFields;
//int inNative;
//int inDataLength;
short inErr,shFields,inNative,inDataLength;
unsigned char temp[48],temp2[12];
short fldLength,nSgnalStrengthPercent;


    // Extract data from event buffer
    ushInitStandardFlexi((unsigned char *)pobCSCLNT->EventDataBuf);
    //shVarGetData(VCS_FLD_CONN_STATUS,  (unsigned char*)&pobCSCLNT->bConnStatus, sizeof(short), (unsigned short*)&inDataLength);
    // MLOULOU
#if 1
    //shVarGetData(VCS_FLD_CONN_STATUS,  (unsigned char*)&pobCSCLNT->bConnStatus, sizeof(short), (unsigned short*)&inDataLength);
    // MLOULOU
 	#ifdef _TARG_68000
  		shRetVal = shGetRecordLength((unsigned char *)pobCSCLNT->EventDataBuf,(int*)&fldLength);
	#elif __thumb //predator
  		shRetVal = shGetRecordLength((unsigned char *)pobCSCLNT->EventDataBuf,(short*)&fldLength);
	#endif //_TARG_68000

	//inPrintISOPacket("EventDataBuf", (unsigned char *)pobCSCLNT->EventDataBuf, (int)fldLength);

    for(shFields = 0; shFields < MAX_STATUS_FIELDS; shFields++)
        {
            switch(StatusIDs[shFields])
                {
                    case VCS_FLD_CONN_STATUS:
                        shVarGetData(VCS_FLD_CONN_STATUS,  (unsigned char*)&pobCSCLNT->bConnStatus, sizeof(short), (unsigned short*)&inDataLength);
                        //pdebug(("VCS_FLD_CONN_STATUS %d", pobCSCLNT->bConnStatus));
							shConnectionStatus=pobCSCLNT->bConnStatus;
                        break;
                    // TODO: KV1 Switch to Percentage
#if 0
                    case VCS_FLD_STATUS_SIGNAL_STRENGTH_ACTUAL:
                        shVarGetData(VCS_FLD_STATUS_SIGNAL_STRENGTH_ACTUAL, (unsigned char *) &inNative, sizeof(int), (unsigned short*)&inDataLength);
                        pdebug (("inInitCSCLNTComm:Data:VCS_FLD_STATUS_SIGNAL_STRENGTH_ACTUAL:%d", inNative));
                        srGDS.srWirelessSignalStatus.lnRawValue = inNative;
                        break;
#else
				case VCS_FLD_STATUS_SIGNAL_STRENGTH_PERCNT:
						shSignalStrength=0;
						memset(temp,0,sizeof(temp));
	      	          //shVarGetData(VCS_FLD_STATUS_SIGNAL_STRENGTH_PERCNT, (unsigned char *) &temp, sizeof(short), (unsigned short*)&inDataLength);
			   			//pdebug (("inInitCSCLNTComm:Data:VCS_FLD_STATUS_SIGNAL_STRENGTH_PERCNT:%s", temp));
				 		//inPrintISOPacket(temp, "-",1);
  						shVarGetField((unsigned char *)pobCSCLNT->EventDataBuf,VCS_FLD_STATUS_SIGNAL_STRENGTH_PERCNT,(unsigned char *)&shSignalStrength,sizeof(short),(unsigned short*)&fldLength);
  						//sprintf(temp,"+++++Signal percent = %d+++++",shSignalStrength);
						//pdebug ((0x8L, temp));
						//inPrintISOPacket(temp, "-",1);
  						//vdDisplayAt(1,5,temp, CLR_EOL);
						//get_char();
					//						pdebug(("shRetVal=%d,VCS_FLD_STATUS_SIGNAL_STRENGTH_PERCNT=%d",shRetVal,nSgnalStrengthPercent));
                  //      srGDS.srWirelessSignalStatus.shPercentage = inNative;
			   break;
#endif
                    default:
                        break;
                }
        }
#endif


    shVarGetUnsignedInt(VCS_FLD_SESS_ERROR, (unsigned short *) &inErr);
    shVarGetUnsignedInt(VCS_FLD_SESS_NATIVE, (unsigned short *) &inNative);
    //pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_ERROR:%d", inErr));
    //pdebug (("inInitCSCLNTComm:Data:VCS_FLD_SESS_NATIVE:%d", inNative));

    if ( inErr != 0 )
    {
            shRetVal = VS_ERROR;
    }
    return shRetVal;
}

static short shGetStatus(CSCLNT_OBJECT *pobCSCLNT)
{
	short shRetVal = VS_SUCCESS;

    // Set up event to recv from server
    pobCSCLNT->shEsmCount = 1;
    pobCSCLNT->shEsmList[0] = VCS_EVT_STATUS_RESP;

    // Read event from server
    shRetVal = shReadEventFromSvr(10000, pobCSCLNT);

    if ( shRetVal == VS_SUCCESS )
    {
            shRetVal = shExtractStatus (pobCSCLNT);
    }

    return shRetVal;

}

/*******************************************************************
*    Function Name:  inDoCommSvrStatus()
*
*    Description:  MAM Addition. Processes PIPE events during IDLE. If a pipe
*					event is received, check for a CUSTOM EVENT.
*    Programmer
********************************************************************/
extern unsigned char pucMAMEventData[450];
extern unsigned short shMAMEventDataSize;

int inDoCommSvrStatus(void)
{
short retVal;
CSCLNT_OBJECT *pobCSCLNT;

    //LOG_PRINTFF((EESL_DEBUG_GLOBAL,"inDoCommSvrStatus"));
    pobCSCLNT = (CSCLNT_OBJECT *)obCommunication.Data;
    MEMCLR (pobCSCLNT->EventDataBuf, sizeof (pobCSCLNT->EventDataBuf));
    memcpy (pobCSCLNT->EventDataBuf, pucMAMEventData, sizeof(pucMAMEventData));
    retVal = shExtractStatus(pobCSCLNT);
    if ( retVal == VS_SUCCESS )
        {
            // Current/last measurement value as percentage
            // Convert to index for graphic
//            srGDS.fConnectionStatus = pobCSCLNT->bConnStatus;
//            srGDS.srWirelessSignalStatus.shGraphicIndex = shComputeGraphicIndex ((int)srGDS.srWirelessSignalStatus.shPercentage, 4);
//            pdebug (("RECEIVED  Percent %d, Index %d ", srGDS.srWirelessSignalStatus.shPercentage, srGDS.srWirelessSignalStatus.shGraphicIndex));
        }

    return retVal;
}

int inInitCommServer(TRANSACTION_OBJECT *pobTran)
{
	if(shGetCommLinkType()!= CSCLNT_COMM)
		return(VS_SUCCESS);

	inInitializeComm(CSCLNT_COMM);
	return(VS_SUCCESS);
}

/*******************************************************************
*    Function Name:  inCheckStatus()
*
*    Description:  	this procedure sends a command to the commserver to get the signal strength and check
*					signal status
*    Programmer		albert_d1
********************************************************************/
int inCheckStatus(TRANSACTION_OBJECT *pobTran)
{
	COMM_OBJECT *pobCommunication;
	CSCLNT_OBJECT *pobCSCLNT;
	short retval;
	static short counter=5;
	static short init=10;
	unsigned char temp[10+1];

	if(shGetCommLinkType()!= CSCLNT_COMM)
		return(VS_SUCCESS);

	if(get_console(0)==-1)//softpay is not active (-1),softpay active (1)
		return(VS_SUCCESS);

	counter--;

	if(counter>0)
	{
		//pdebug(("counter=%d",counter));
		return(VS_SUCCESS);
	}

	counter=40;

	if(obCommunication.inCheck)
	{
		pobCSCLNT = (CSCLNT_OBJECT *)obCommunication.Data;
		retval=shRequestStatus(pobCSCLNT, VS_FALSE);
	}

  	if ( retval == VS_SUCCESS )
   	{
		//vdDisplayAt(1, 7, "VS_SUCCESS", CLR_EOL);
    	retval = shGetStatus(pobCSCLNT);
    }
	return(VS_SUCCESS);
}

/*******************************************************************
*    Function Name:  vdDisplaySignalStrength()
*
*    Description:  	this procedure displays the signal strength on the console. this is invoked during
*					idle loop.
*    Programmer		albert_d1
********************************************************************/
int inDisplaySignalStrength(TRANSACTION_OBJECT *pobTran)
{
	//pdebug(("inSignalStatus=%d,inStatus=%d",inSignalStatus,inStatus));
	//if((inSignalStatus <= 0) && (inStatus != 0))
	//pdebug(("inSignalStatus=%d",inSignalStatus));
	

	if(shGetCommLinkType()!= CSCLNT_COMM)
		return(VS_SUCCESS);

	vdSetEntryFont(VS_TRUE);

	if(shSignalStrength <= 0 || shConnectionStatus <= 0)
	{
		 gotoxy(1, 4);
       	 vdDisplayFontChar(UTILITY_FONT, 30);
		 gotoxy(1, 6);
       	 vdDisplayFontChar(UTILITY_FONT, 24);
	}
	else if (shSignalStrength >= 1 && shConnectionStatus > 0)
	{
		//gotoxy(1, 4);
		if ((shSignalStrength >= 81) && (shSignalStrength <= 100))
		{
			//pdebug(("***** #5 bars *****"));
			gotoxy(1, 4);
				vdDisplayFontChar(UTILITY_FONT, 29);/*3 bar*/
			gotoxy(1, 6);
				vdDisplayFontChar(UTILITY_FONT, 26); /*2 bar*/
		}
		else if ((shSignalStrength >= 61) && (shSignalStrength <= 80))
		{
			//pdebug(("***** #4 bars *****"));
			gotoxy(1, 4);
				vdDisplayFontChar(UTILITY_FONT, 28);/*2 bar*/
			gotoxy(1, 6);
				vdDisplayFontChar(UTILITY_FONT, 26); /*2 bar*/
		}
		else if ((shSignalStrength >= 41) && (shSignalStrength <= 60))
		{
			//pdebug(("***** #3 bars *****"));
			gotoxy(1, 4);
				vdDisplayFontChar(UTILITY_FONT, 27);/*1 bar*/
			gotoxy(1, 6);
				vdDisplayFontChar(UTILITY_FONT, 26); /*2 bar*/
		}
		else if ((shSignalStrength >= 21) && (shSignalStrength <= 40))
		{
			//pdebug(("***** #2 bars *****"));
			gotoxy(1, 4);
				vdDisplayFontChar(UTILITY_FONT, 30);/*empty*/
			gotoxy(1, 6);
				vdDisplayFontChar(UTILITY_FONT, 26); /*2 bar*/
		}
		else if ((shSignalStrength >= 1) && (shSignalStrength <= 20))
		{
			//pdebug(("***** #1 bar *****"));
			gotoxy(1, 4);
				vdDisplayFontChar(UTILITY_FONT, 30);/*empty*/
			gotoxy(1, 6);
				vdDisplayFontChar(UTILITY_FONT, 25); /*1 bar*/
		}
		//gotoxy(1, 6);
		//vdDisplayFontChar(UTILITY_FONT, WIFI_CHAR1);
	}
	vdSetIdleFont(VS_TRUE);

	return(VS_SUCCESS);
}


// Function: inBeginCSCLNTComm
// Description: Establishes connection sets up context
//


#endif //CSCLNT_DEFINED
